﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Nvigorate.Data.Query;
using Nvigorate.Relational.Builders;
using Nvigorate.Relational.Mapping;
using Nvigorate.Relational.Mapping.Index;
using Nvigorate.Relational.Mapping.Interface;
using Nvigorate.Relational.Repository;
using Nvigorate.TestObjects;

namespace Nvigorate.Test.Relational.Repository
{
    [TestClass]
    public class DeleteBuilderTests
    {
        #region Build Tests

        [TestMethod]
        public void Build_CreatesDeleteStatement()
        {
            // Arrange
            var sourceMap = GetValidPersonMap();
            var person = new Person {SocialSecurity = "123456789"};
            var repositoryMapIndex = new Mock<IRepositoryMapIndex>();
            var builder = new DeleteBuilder(sourceMap, PersistenceDecorator.Create(person));

            // Act
            var query = builder.Build();

            // Assert
            Assert.IsInstanceOfType(query, typeof(Delete));
            Assert.AreEqual("Person", ((Delete)query).Table.Name);
        }

        [TestMethod]
        public void Build_CreatesWhereClauseWithPrimaryKey()
        {
            // Arrange
            var sourceMap = GetValidPersonMap();
            var person = new Person { SocialSecurity = "123456789" };
            var repositoryMapIndex = new Mock<IRepositoryMapIndex>();
            var builder = new DeleteBuilder(sourceMap, PersistenceDecorator.Create(person));

            // Act
            var query = builder.Build() as Delete;

            // Assert
            Assert.AreEqual(1, query.Qualifiers.Count);
            var where = query.Qualifiers[0] as Where;
            Assert.IsNotNull(where);
            Assert.AreEqual(1, where.SearchCriteria[0].Criteria.Count);
            QueryAssert.EqualCriterion(where.SearchCriteria[0].Criteria[0], "SSN", person.SocialSecurity);
        }

        #endregion

        #region Private Methods

        private ISourceMap GetValidPersonMap()
        {
            var sourceMap = new SourceMap("Person") { SourceName = "Person" };
            sourceMap.Assignments.Add(new MemberAssignment(
                                          new AssignmentPoint("Person", "SSN"),
                                          new AssignmentPoint("Person", "SocialSecurity")) {PrimaryKey = true});
            sourceMap.Assignments.Add(new MemberAssignment(
                                          new AssignmentPoint("Person", "firstName"),
                                          new AssignmentPoint("Person", "FirstName")));

            return sourceMap;
        }

        #endregion

    }
}
